package com.kjsdfgk.hjmdsf.livev2.mvp.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.blankj.utilcode.util.TimeUtils;
import com.google.android.material.navigation.NavigationView;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;

import com.kjsdfgk.hjmdsf.app.entity.Account;
import com.kjsdfgk.hjmdsf.live.mvp.bean.PingtaiBean;
import com.kjsdfgk.hjmdsf.live.mvp.bean.VersionEntity;
import com.kjsdfgk.hjmdsf.live.mvp.ui.activity.GridLineItemDecoration;
import com.kjsdfgk.hjmdsf.live.mvp.ui.activity.LiveAdapter;
import com.kjsdfgk.hjmdsf.livev2.di.component.DaggerLiveV2Component;
import com.kjsdfgk.hjmdsf.livev2.mvp.contract.LiveV2Contract;
import com.kjsdfgk.hjmdsf.livev2.mvp.presenter.LiveV2Presenter;
import com.kjsdfgk.hjmdsf.charge.mvp.ui.activity.MemberChargeActivity;
import com.kjsdfgk.hjmdsf.login.mvp.ui.activity.LoginActivity;
import com.kjsdfgk.hjmdsf.register.mvp.ui.activity.RegisterActivity;
import com.lksdkjs.live.R;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;


import java.util.List;

import butterknife.BindView;
import cn.leancloud.AVUser;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 04/13/2020 12:47
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class LiveV2Activity extends BaseActivity<LiveV2Presenter> implements LiveV2Contract.View, NavigationView.OnNavigationItemSelectedListener, SwipeRefreshLayout.OnRefreshListener {

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerLiveV2Component //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_live_v2; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @BindView(R.id.toolbarxxx)
    Toolbar toolbar;
    TextView memberName;
    TextView expireTime;
    TextView invoteCode;
    RxPermissions mRxPermissions;
    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        mRxPermissions = new RxPermissions(this);

//        Toolbar toolbar = findViewById(R.id.toolbar);
         setSupportActionBar(toolbar);

        toolbar.setNavigationIcon(R.mipmap.ic_launcher);
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        View headerView = navigationView.getHeaderView(0);
        memberName = headerView.findViewById(R.id.navigation_member_name);
        expireTime = headerView.findViewById(R.id.navigation_expire_time);
        invoteCode = headerView.findViewById(R.id.navigation_invite_code);


        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
        navigationView.setNavigationItemSelectedListener(this);

        mPresenter.getPingTaiJson();
        mPresenter.checkVersion();
        mSwipeRefreshLayout.setOnRefreshListener(this);
        final GridLayoutManager mLayoutManager = new GridLayoutManager(this, 3);
        mRecyclerView.setLayoutManager(mLayoutManager);
        GridLineItemDecoration mDecor = new GridLineItemDecoration(this, 0xFFe1e1e1, 3, 1);
        mRecyclerView.addItemDecoration(mDecor);
        ArmsUtils.configRecyclerView(mRecyclerView, mLayoutManager);

//        mPresenter.loginDevice();

        mPresenter.generateDeviceUser( );
    }

    @Override
    public RxPermissions getRxPermissions() {
        return mRxPermissions;
    }

    @Override
    public void showLoginDlg() {
        QMUIDialog.MessageDialogBuilder builder = new QMUIDialog.MessageDialogBuilder(this);
        builder.setTitle("系统提示");
        builder.setMessage("您尚未登录");

        builder.addAction("马上注册", (dialog, index) -> {
            dialog.cancel();
            Intent intent = new Intent(this , RegisterActivity.class);
            startActivity(intent);
        });
        builder.addAction("立即登录", (dialog, index) -> {
            dialog.cancel();
            Intent intent = new Intent(this , LoginActivity.class);
            startActivity(intent);

        });


        builder.show();
    }



    @Override
    public void showLoading(String key) {
        mSwipeRefreshLayout.setRefreshing(true);
    }

    @Override
    public void hideLoading() {
        mSwipeRefreshLayout.setRefreshing(false);
    }

    @Override
    public boolean isCancel() {
        return loadingDialog.isCancel(null);
    }

    @Override
    public void onBackPressedSupport() {

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }



    private boolean isOnKeyBacking = false;
    private final Handler mainLoopHandler = new Handler(Looper.getMainLooper());
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (isOnKeyBacking) {
                mainLoopHandler.removeCallbacks(onBackTimeThread);
                isOnKeyBacking = false;
                finish();
            }else {
                isOnKeyBacking = true;
                mainLoopHandler.postDelayed(onBackTimeThread, 2000);
                showMessage("再按一下退出");

            }
            return true;
        }else {
            return super.onKeyDown(keyCode, event);
        }
    }
    private final Runnable onBackTimeThread = new Runnable(){
        public void run() {
            isOnKeyBacking = false;
        }
    };
//    @Override
//    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
//        int id = item.getItemId();
//
//
//
//        DrawerLayout drawer = findViewById(R.id.drawer_layout);
//        drawer.closeDrawer(GravityCompat.START);
//        return true;
//    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_menu_item_info:

                break;

            case R.id.navigation_menu_item_cache:

                break;

            case R.id.navigation_menu_item_exit:
                mPresenter.logOut();
                break;

            case R.id.navigation_menu_item_flock:

                break;

            case R.id.navigation_menu_item_version:

                break;

            case R.id.navigation_menu_item_member:
                Account account = mPresenter.getAccount();
                if (account!=null){
                    Intent intent = new Intent(this , MemberChargeActivity.class);
                    launchActivity(intent);
                }else {
                    Intent intent = new Intent(this , LoginActivity.class);
                    launchActivity(intent);
                }

                break;

            case R.id.navigation_menu_item_integral:
                //积分

                break;

            case R.id.navigation_menu_item_lock:

                break;

            default:

                break;
        }
    //    DrawerLayout drawer = findViewById(R.id.drawer_layout);
    //    drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    @BindView(R.id.live_tips)
    TextView liveTips;



    LiveAdapter mAdapter;
    @Override
    public void showPingTaiJson(List<PingtaiBean> datas) {
        mRecyclerView.setAdapter(mAdapter = new LiveAdapter(datas));
    }

    @Override
    public void showNewVersion(VersionEntity updateVersion) {
        QMUIDialog.MessageDialogBuilder builder = new QMUIDialog.MessageDialogBuilder(this);
        builder.setTitle("发现新版本--v" + updateVersion.getVersionName());
        builder.setMessage(updateVersion.getUpdateMessage());
        builder.addAction("立即更新", (dialog, index) -> {
//            showMessage("开始下载", TastyToast.INFO);
//            Intent intent = new Intent(MainActivity.this, UpdateDownloadService.class);
//            intent.putExtra("updateVersion", updateVersion);
//            startService(intent);
            Intent intent= new Intent();
            intent.setAction("android.intent.action.VIEW");
            Uri content_url = Uri.parse(updateVersion.getApkDownloadUrl());
            intent.setData(content_url);
            startActivity(intent);

        });
  /*      builder.addAction("稍后更新", (dialog, index) -> dialog.dismiss());
        builder.addAction("该版本不再提示", (dialog, index) -> {
            //保存版本号，用户对于此版本选择了不在提示
            presenter.setIgnoreUpdateVersionCode(updateVersion.getVersionCode());
            dialog.dismiss();
        });*/
        builder.setCancelable(false);
        builder.setCanceledOnTouchOutside(false);
        builder.show();
    }

    @Override
    public void showAccount(AVUser user) {
        memberName.setText("用    户："+user.getObjectId().substring(0,10));
        expireTime.setText("到    期："+ TimeUtils.millis2String(user.getLong("expireTime")));
        String id = user.getObjectId();
        invoteCode.setText("邀请ID："+ (id.substring(id.length()-6 ,id.length()-1)).toUpperCase());
    }

    @Override
    public void showAccount(Account user) {
        memberName.setText("用    户："+user.getName());
        expireTime.setText("到    期："+TimeUtils.millis2String(Long.parseLong(user.getVip())*1000) );
        invoteCode.setText("邀请ID："+  user.getId());
    }
    @Override
    public void showInitView() {
        memberName.setText("用    户：-" );
        expireTime.setText("到    期：-" );
        invoteCode.setText("邀请ID：-");
    }
    @Override
    public void onRefresh() {
        mPresenter.getPingTaiJson();
    }
}
